package com.atguigu.yygh.common.exception;

import com.atguigu.yygh.common.result.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * Created with IntelliJ IDEA
 *
 * @Date: 2022/12/6 - 15:16
 * @Author: Hyoung
 * @Description: 统一异常处理
 */
@RestControllerAdvice // 以json的形式返回
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public R error(Exception e) {
        // 打印错误跟踪栈
        log.error(ExceptionUtils.getStackTrace(e));
        return R.error();
    }

    @ExceptionHandler(BadSqlGrammarException.class)
    public R error(BadSqlGrammarException e) {

        log.error(ExceptionUtils.getStackTrace(e));
        return R.error().message("sql语法错误");
    }

    @ExceptionHandler(YyghException.class)
    public R error(YyghException e) {
        log.info("error(YyghException e)");
//        e.printStackTrace();
        log.error(ExceptionUtils.getStackTrace(e));
        return R.error().message(e.getMsg()).code(e.getCode());
    }

}
